{
    "cells": [
        {
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "view-in-github"
            },
            "source": [
                "<a href=\"https://colab.research.google.com/github/AI4Finance-Foundation/ElegantRL/blob/master/tutorial_LunarLanderContinuous_v2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "c1gUG3OCJ5GS"
            },
            "source": [
                "# **LunarLanderContinuous-v2 Example in ElegantRL**\n",
                "\n",
                "\n",
                "\n",
                "\n"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "FGXyBBvL0dR2"
            },
            "source": [
                "# **Task Description**\n",
                "\n",
                "[LunarLanderContinuous-v2](https://gym.openai.com/envs/LunarLanderContinuous-v2) is a robotic control task. The goal is to get a Lander to rest on the landing pad. If lander moves away from landing pad it loses reward back. Episode finishes if the lander crashes or comes to rest, receiving additional -100 or +100 points."
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "DbamGVHC3AeW"
            },
            "source": [
                "# **Part 1: Install ElegantRL**"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 1,
            "metadata": {
                "colab": {
                    "base_uri": "https://localhost:8080/"
                },
                "id": "U35bhkUqOqbS",
                "outputId": "0acfcd5b-ebfe-4dba-dd65-10f5e9a3a58e"
            },
            "outputs": [
                {
                    "name": "stdout",
                    "output_type": "stream",
                    "text": [
                        "Collecting git+https://github.com/AI4Finance-LLC/ElegantRL.git\n",
                        "  Cloning https://github.com/AI4Finance-LLC/ElegantRL.git to /tmp/pip-req-build-q0f_9pry\n",
                        "  Running command git clone -q https://github.com/AI4Finance-LLC/ElegantRL.git /tmp/pip-req-build-q0f_9pry\n",
                        "Requirement already satisfied: gym in /usr/local/lib/python3.7/dist-packages (from elegantrl==0.3.3) (0.17.3)\n",
                        "Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from elegantrl==0.3.3) (3.2.2)\n",
                        "Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from elegantrl==0.3.3) (1.19.5)\n",
                        "Collecting pybullet\n",
                        "  Downloading pybullet-3.2.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl (90.8 MB)\n",
                        "\u001b[K     |████████████████████████████████| 90.8 MB 291 bytes/s \n",
                        "\u001b[?25hRequirement already satisfied: torch in /usr/local/lib/python3.7/dist-packages (from elegantrl==0.3.3) (1.10.0+cu111)\n",
                        "Requirement already satisfied: opencv-python in /usr/local/lib/python3.7/dist-packages (from elegantrl==0.3.3) (4.1.2.30)\n",
                        "Collecting box2d-py\n",
                        "  Downloading box2d_py-2.3.8-cp37-cp37m-manylinux1_x86_64.whl (448 kB)\n",
                        "\u001b[K     |████████████████████████████████| 448 kB 70.5 MB/s \n",
                        "\u001b[?25hRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from gym->elegantrl==0.3.3) (1.4.1)\n",
                        "Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from gym->elegantrl==0.3.3) (1.5.0)\n",
                        "Requirement already satisfied: cloudpickle<1.7.0,>=1.2.0 in /usr/local/lib/python3.7/dist-packages (from gym->elegantrl==0.3.3) (1.3.0)\n",
                        "Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from pyglet<=1.5.0,>=1.4.0->gym->elegantrl==0.3.3) (0.16.0)\n",
                        "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->elegantrl==0.3.3) (0.11.0)\n",
                        "Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->elegantrl==0.3.3) (3.0.6)\n",
                        "Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->elegantrl==0.3.3) (1.3.2)\n",
                        "Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->elegantrl==0.3.3) (2.8.2)\n",
                        "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib->elegantrl==0.3.3) (1.15.0)\n",
                        "Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch->elegantrl==0.3.3) (3.10.0.2)\n",
                        "Building wheels for collected packages: elegantrl\n",
                        "  Building wheel for elegantrl (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
                        "  Created wheel for elegantrl: filename=elegantrl-0.3.3-py3-none-any.whl size=183567 sha256=a2b2116b1f175b6cad721c1dfeba30620a45100aa1a7e65fe9c19df809fe68d3\n",
                        "  Stored in directory: /tmp/pip-ephem-wheel-cache-ltz2mxds/wheels/52/9a/b3/08c8a0b5be22a65da0132538c05e7e961b1253c90d6845e0c6\n",
                        "Successfully built elegantrl\n",
                        "Installing collected packages: pybullet, box2d-py, elegantrl\n",
                        "Successfully installed box2d-py-2.3.8 elegantrl-0.3.3 pybullet-3.2.1\n"
                    ]
                }
            ],
            "source": [
                "# install elegantrl library\n",
                "!pip install git+https://github.com/AI4Finance-LLC/ElegantRL.git"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "UVdmpnK_3Zcn"
            },
            "source": [
                "# **Part 2: Import Packages**\n",
                "\n",
                "\n",
                "*   **elegantrl**\n",
                "*   **OpenAI Gym**: a toolkit for developing and comparing reinforcement learning algorithms.\n",
                "\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 2,
            "metadata": {
                "id": "AAPdjovQrTpE"
            },
            "outputs": [],
            "source": [
                "import gym\n",
                "from elegantrl.agents import AgentModSAC\n",
                "from elegantrl.train.config import get_gym_env_args, Config\n",
                "from elegantrl.train.run import *\n",
                "\n",
                "gym.logger.set_level(40)  # Block warning"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "z2Ik5cDoyPGU"
            },
            "source": [
                "# **Part 3: Get environment information**"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 3,
            "metadata": {
                "colab": {
                    "base_uri": "https://localhost:8080/"
                },
                "id": "wwkZXiHtyV6f",
                "outputId": "24720b42-25ca-4491-8fff-c6e7470dedf5"
            },
            "outputs": [
                {
                    "data": {
                        "text/plain": [
                            "{'env_name': 'LunarLanderContinuous-v2',\n",
                            " 'num_envs': 1,\n",
                            " 'max_step': 1000,\n",
                            " 'state_dim': 8,\n",
                            " 'action_dim': 2,\n",
                            " 'if_discrete': False}"
                        ]
                    },
                    "execution_count": 3,
                    "metadata": {},
                    "output_type": "execute_result"
                }
            ],
            "source": [
                "get_gym_env_args(gym.make(\"LunarLanderContinuous-v2\"), if_print=False)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "3n8zcgcn14uq"
            },
            "source": [
                "# **Part 4: Specify Agent and Environment**\n",
                "\n",
                "*   **agent**: chooses a agent (DRL algorithm) from a set of agents in the [directory](https://github.com/AI4Finance-Foundation/ElegantRL/tree/master/elegantrl/agents).\n",
                "*   **env_func**: the function to create an environment, in this case, we use gym.make to create BipedalWalker-v3.\n",
                "*   **env_args**: the environment information.\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 5,
            "metadata": {
                "id": "E03f6cTeajK4"
            },
            "outputs": [],
            "source": [
                "env_func = gym.make\n",
                "env_args = {\n",
                "    \"env_num\": 1,\n",
                "    \"env_name\": \"LunarLanderContinuous-v2\",\n",
                "    \"max_step\": 1000,\n",
                "    \"state_dim\": 8,\n",
                "    \"action_dim\": 2,\n",
                "    \"if_discrete\": False,\n",
                "    \"target_return\": 200,\n",
                "    \"id\": \"LunarLanderContinuous-v2\",\n",
                "}\n",
                "args = Config(AgentModSAC, env_class=env_func, env_args=env_args)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "rcFcUkwfzHLE"
            },
            "source": [
                "# **Part 4: Specify hyper-parameters**\n",
                "A list of hyper-parameters is available [here](https://elegantrl.readthedocs.io/en/latest/api/config.html)."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 6,
            "metadata": {
                "id": "9WCAcmIfzGyE"
            },
            "outputs": [],
            "source": [
                "args.target_step = args.max_step\n",
                "args.gamma = 0.99\n",
                "args.eval_times = 2**5\n",
                "args.random_seed = 2022"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "z1j5kLHF2dhJ"
            },
            "source": [
                "# **Part 5: Train and Evaluate the Agent**\n",
                "\n",
                "\n",
                "\n",
                "\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": 7,
            "metadata": {
                "colab": {
                    "base_uri": "https://localhost:8080/"
                },
                "id": "KGOPSD6da23k",
                "outputId": "84157a77-bcfa-406d-c25e-d3dea0e8fc20"
            },
            "outputs": [
                {
                    "name": "stdout",
                    "output_type": "stream",
                    "text": [
                        "| Arguments Remove cwd: ./LunarLanderContinuous-v2_ModSAC_2022\n"
                    ]
                },
                {
                    "name": "stderr",
                    "output_type": "stream",
                    "text": [
                        "/home/adhi/ElegantRL/.env-erl/lib/python3.10/site-packages/gym/utils/passive_env_checker.py:241: DeprecationWarning: `np.bool8` is a deprecated alias for `np.bool_`.  (Deprecated NumPy 1.24)\n",
                        "  if not isinstance(terminated, (bool, np.bool8)):\n"
                    ]
                },
                {
                    "name": "stdout",
                    "output_type": "stream",
                    "text": [
                        "| Evaluator:\n",
                        "| `step`: Number of samples, or total training steps, or running times of `env.step()`.\n",
                        "| `time`: Time spent from the start of training to this moment.\n",
                        "| `avgR`: Average value of cumulative rewards, which is the sum of rewards in an episode.\n",
                        "| `stdR`: Standard dev of cumulative rewards, which is the sum of rewards in an episode.\n",
                        "| `avgS`: Average of steps in an episode.\n",
                        "| `objC`: Objective of Critic network. Or call it loss function of critic network.\n",
                        "| `objA`: Objective of Actor network. It is the average Q value of the critic network.\n",
                        "################################################################################\n",
                        "ID     Step    Time |    avgR   stdR   avgS  stdS |    expR   objC   objA   etc.\n",
                        "0  5.12e+02       8 | -209.81  126.8    125    38 |   -2.32   5.02   0.01   0.35\n",
                        "0  2.10e+04     213 |   42.28  134.3    251    90 |   -0.04   4.05  23.89   0.16\n",
                        "0  4.15e+04     423 |    2.52   81.0    307    83 |    0.45   3.24  39.48   0.06\n",
                        "0  6.20e+04     625 |  -12.21   28.4    319    68 |   -0.10   2.42  31.58   0.05\n",
                        "0  8.24e+04     820 |  -67.12   38.4    325    61 |   -0.14   2.40  24.88   0.03\n"
                    ]
                }
            ],
            "source": [
                "train_agent(args)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {
                "id": "JPXOxLSqh5cP"
            },
            "source": [
                "Understanding the above results::\n",
                "*   **Step**: the total training steps.\n",
                "*  **MaxR**: the maximum reward.\n",
                "*   **avgR**: the average of the rewards.\n",
                "*   **stdR**: the standard deviation of the rewards.\n",
                "*   **objA**: the objective function value of Actor Network (Policy Network).\n",
                "*   **objC**: the objective function value (Q-value)  of Critic Network (Value Network)."
            ]
        }
    ],
    "metadata": {
        "accelerator": "GPU",
        "colab": {
            "collapsed_sections": [],
            "include_colab_link": true,
            "name": "tutorial_LunarLanderContinuous-v2.ipynb",
            "provenance": []
        },
        "kernelspec": {
            "display_name": "Python 3",
            "name": "python3"
        },
        "language_info": {
            "codemirror_mode": {
                "name": "ipython",
                "version": 3
            },
            "file_extension": ".py",
            "mimetype": "text/x-python",
            "name": "python",
            "nbconvert_exporter": "python",
            "pygments_lexer": "ipython3",
            "version": "3.10.6"
        }
    },
    "nbformat": 4,
    "nbformat_minor": 0
}
